`timescale 1ns / 1ps

module funct(
    input clk, 
    input [2:0] n,//阶层 n 
    input rst_n, //系统复位，低电平有效 
    output [15:0] result//阶层结果
    );

    reg [2:0] current_n=0; // 当前计算的阶层值
    reg [15:0] fact_result=1; // 阶层计算的结果
    reg [3:0] cur_state=0, next_state=0; // 状态机的状态
    reg [15:0] result_reg=1;

    assign result = result_reg;

    // 定义状态
    localparam IDLE = 4'd0, CALC = 4'd1, DONE = 4'd2;

    // 状态机：根据状态执行相应操作
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            cur_state <= 0;
            next_state <= 0;
        end else begin
            cur_state <= next_state;
        end
    end

    // 状态机的逻辑
    always @(*) begin
        case(cur_state)
            IDLE: begin
                if (n != current_n) begin
                    next_state = CALC;
                end else begin
                    next_state = IDLE;
                end
            end

            CALC: begin
                if (current_n == 0) begin
                    fact_result = 1;
                end else begin
                    fact_result = fact_result * current_n;
                end
                if (current_n == n) begin
                    next_state = DONE;
                end else begin
                    next_state = CALC;
                end
            end

            DONE: begin
                result_reg = fact_result;
                next_state = IDLE;
            end

            default: next_state = IDLE;
        endcase
    end


endmodule
